<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>TestCloudCall</title>
    <body>

        <div>
            <label>主叫号码：</label>
            <textarea id="txPhoneA" rows="1">13418035053</textarea>
        </div>
        <div>
            <label>被叫号码：</label>
            <textarea id="txPhoneB" rows="1">02038881773</textarea>
        </div>
        <div>
            <label>显示号码：</label>
            <textarea id="showNum" rows="1">057128204523</textarea>
        </div>
        <div>
            <label>机器码&nbsp&nbsp：</label>
            <textarea id="txToken" rows="1">111222333</textarea>
        </div>
        <div>
            <label>任务id：</label>
            <textarea id="callTaskId" rows="1">11122d33</textarea>
        </div>
        <div>
            <label>任务包id：</label>
            <textarea id="packageId" rows="1">11122d33</textarea>
        </div>
        <div>
            <label>&nbsp&nbsp ID &nbsp&nbsp：</label>
            <textarea id="txUserId" rows="1">12345678</textarea>
        </div>

        <button id="btnConnect" onclick="init()">连接</button>
        <button id="btnDisconnect" onclick="disconnect()">关闭连接</button>
        <button id="btnCall" onclick="call()">呼叫</button>
        <button id="btnInterrupt" onclick="interrupte()">中断</button>
        <!--<button id="btnChangePc" onclick="btnChangePc()">确定切换电脑外呼</button>-->
        <!--<button id="btnChangePcNot" onclick="btnChangePcNot()">不切换电脑外呼</button>-->
        <!--<button id="btnTest" onclick="createWbs()">大量连接</button>-->
<!---style="width: 100%;"-->
<div style="width: 100%;height:100%">
        <div   style="display: inline;float: left;height: auto;width: 50%">
            <textarea id="txResult" rows="20" cols="40" style="width: 100%;height: 600px"></textarea>
        </div>
        <div   style="display: inline;float: left;height: auto;width:50%">
            <textarea id="txResult1" rows="20" cols="40" style="width: 100%;height: 600px" >通话识别结果:</textarea>
        </div>
</div>
        <script type="text/javascript" src="/wbs/js/jquery-1.7.2.min.js"></script>
        <script type="text/javascript">
           var env = "local_test";
     //      var env = "pro";
    //         var env = "test";
//            var env = "pro44";

            var showNum = "";
            var sessionId;
            var webSocket;
            //先获取用户ID
            document.getElementById("txToken").value = uuid(16, 16);
            var token = document.getElementById("txToken").value;
            document.getElementById("txUserId").value = "13570";// uuid(8, 16);
            var userId = document.getElementById("txUserId").value;

            var websocketList = new Array();
            var url;

            function createWbs(){
                var i = 1024;
                var count = 0;
                var temp;

                for(;i<=65535;i++) {

                    token = document.getElementById("txToken").value +"_"+ i.toString();

                    url= "ws://172.16.3.200:80/wbs/wbsForBrowser?token=" + token+ "&userId=" + userId;
                        try {
                            temp = new WebSocket(url);
                            temp.onopen = function (event) {
//                                console.log("------------websocket on open!-----------" + i);
                            };

                            temp.onmessage = function (event) {
                                console.log("------------websocket on onmessage!-----------" + i);
                            };

                            temp.onclose = function (event) {
                                console.log("------------websocket on onclose!-----------" + i);
                            };

                            temp.onerror = function (event) {
                                console.log("------------websocket on onerror!-----------" + i);
                            };
                            websocketList[i] = temp;
                        } catch (e) {
                            console.log("connect max:" + i);
                            break;
                        }
                }

            }

            function init() {
                token = document.getElementById("txToken").value;
                userId = document.getElementById("txUserId").value;
                if(env == "local_test")
                    url= "ws://172.16.6.102:9990/wbs/browser/connect?token=" + token+ "&userId=" + userId;
                else if(env == "test")
                    url = "ws://113.108.202.235:8080/wbs/browser/connect?token=" + token + "&userId=" + userId;
                else if(env == "pro")
                    url = "ws://172.16.200.42:8080/wbs/browser/connect?token=" + token + "&userId=" + userId;
                else if(env == "pro44")
                    url = "ws://172.16.200.44:8080/wbs/browser/connect?token=" + token + "&userId=" + userId;

                webSocket = new WebSocket(url);

                txResult.innerText = "connecting";

                webSocket.onopen = function(event) {
                    console.log("------------websocket on open!-----------");
                    callback(event);
                };

                webSocket.onmessage = function(event) {
                    console.log("------------websocket on onmessage!-----------");
                    callback(event);
                };

                webSocket.onclose = function(event) {
                    console.log("------------websocket on onclose!-----------");
                    callback(event);
                };

                webSocket.onerror = function(event) {
                    console.log("------------websocket on onerror!-----------");
                    callback(event);
                };

                //每100秒发一次心跳包
                //这里的回调不可以加括号()
                setInterval(heartbeat, 15000);

            }

            //代理方法，发送消息到服务器必须用这个方法
            function waitForConnection(todoMethod, interval) {
                if(webSocket.readyState == WebSocket.OPEN) {
                    todoMethod();
                } else {
                    setTimeout(function() {
                        waitForConnection(todoMethod, interval);
                    });
                }

            }
            //外呼
            function call() {
                showNum = document.getElementById("showNum").value
                waitForConnection(function() {
                    try {
                        webSocket.send(JSON.stringify({
                            msgType: "CALL",
                            mainCallPhone: document.getElementById("txPhoneA").value,
                            targetCallPhone: document.getElementById("txPhoneB").value,
                            machineFrom: document.getElementById("txToken").value,
                            callTaskId:document.getElementById("callTaskId").value,
                            packageId:document.getElementById("packageId").value,
                            createUserId: "13570",
                            dataId:"1621",
                            whereFrom:"1",
                            pageFrom:"1",
                            mainCallType:"0",
                            customerName:"wws",
                            showNum:showNum,
                            commitTo:"10",
                            city:"1"

                        }));
                    } catch (e) {
                        console.log("call error");
                        console.log(e);
                    }
                }, 100);
            }

            //
            function btnChangePc() {
                waitForConnection(function() {
                    try {
                        webSocket.send(JSON.stringify({
                            msgType: "changePc",
                            token: document.getElementById("txToken").value,
                            userId: "13570"
                        }));
                    } catch (e) {
                        console.log("call error");
                        console.log(e);
                    }
                }, 100);
            }

            function btnChangePcNot() {
                waitForConnection(function() {
                    try {
                        webSocket.send(JSON.stringify({
                            msgType: "notChangePc",
                            token: document.getElementById("txToken").value,
                            userId: "13570",
                        }));
                    } catch (e) {
                        console.log("call error");
                        console.log(e);
                    }
                }, 100);
            }

            function interrupte(){
                var autoInterrupt = false;
                var url;
                if(env == "local_test")
                    //url= "http://172.16.6.56:8888/cloudcall/call/interruptCall.do";
                    url= "http://172.16.6.102:50808/aliyuncall/callCenter/interruptCall";
                else if(env == "test")
                   url = "http://113.108.202.236:8888/cloudcall/call/interruptCall.do";

                else if(env == "pro")
                    url="http://cloudcall.hfit.ihk.cn:8888/cloudcall/call/interruptCall.do";
                else if(env == "pro44")
                    url = "http://172.16.200.44:8080/cloudcall/call/interruptCall.do";

                $.ajax({
                    type : "get",
                    async: false,
                    url : url+"?"+"pId=0&sessionId="+sessionId+"&autoInterrupt="+autoInterrupt,
                    dataType:"json",
                   // dataType : "jsonp",//数据类型为jsonp
                   // jsonp: "jsonpCallBack",//服务端用于接收callback调用的function名的参数
                    success : function(data){
                            console.log(JSON.parse(data).msg);
                    },
                    error:function(){
                        console.log("发送http请求失败！");
                    }
                });

            }


            //发送心跳包
            var repeatTimes = 0;
            function heartbeat() {
                if(webSocket.readyState == WebSocket.OPEN) {
                    try {
                        webSocket.send(JSON.stringify({
                            msgType: "BEAT",
                            token: token
                        }));
                    } catch (e) {
                        console.log("call error");
                        console.log(e.errMesg);
                    }
                }
            }

            //回调
            var  res = "";
           var str ="";
            function callback(event) {
                var txResult = document.getElementById("txResult");
                var txResult1 = document.getElementById("txResult1");
                console.log(new Date());
                console.log(event);

                switch (event.type) {
                    case "open":
                        txResult.innerText = "已连接，请拨号";
                        hideConnect();
                        break;
                    case "message":
                        console.log(event.data);
                        result = JSON.parse(event.data);
                        if(result.msgType=='WORDS'){ //实时翻译消息

                            var role =result.role;

                            if(role=="customer"){
                                str += "客户:"+result.words+"\r\n";
                            }else{
                                str += "经纪:"+result.words+"\r\n";
                            }
                            txResult1.innerText = str;
                        }else{
                            res += "接收->" + event.data+"\r\n";
                            txResult.innerText = res;
                        }
                        sessionId =result['sessionId'];
                            if(result['msgType'] == 'WEBSOCKET_NOT_RECONNECT_MSG') {
                                webSocket.close();
                                console.log("to do do do close websocket")
                            }
                        break;

                    case "error":
                        txResult.innerText = "onError->" + event.data +"\r\n";
                        hideDisconnect();
                        break;
                    case "close":
                            res +=  "连接已断开"+"\r\n";
                        txResult.innerText = res;
                        hideDisconnect();
                        break;
                        defualt:
                                break;
                }
            }

            function hideConnect() {
                document.getElementById("btnConnect").style.visibility = "hidden";
                document.getElementById("btnDisconnect").style.visibility = "visible";
            }

            function hideDisconnect() {
                document.getElementById("btnConnect").style.visibility = "visible";
                document.getElementById("btnDisconnect").style.visibility = "hidden";
            }

            function disconnect() {
                webSocket.close();
            }

            function uuid (len, radix) {
                // Private array of chars to use
                var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
                var chars = CHARS, uuid = [], i;
                radix = radix || chars.length;

                if (len) {
                    // Compact form
                    for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
                } else {
                    // rfc4122, version 4 form
                    var r;

                    // rfc4122 requires these characters
                    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                    uuid[14] = '4';

                    // Fill in random data.  At i==19 set the high bits of clock sequence as
                    // per rfc4122, sec. 4.1.5
                    for (i = 0; i < 36; i++) {
                        if (!uuid[i]) {
                            r = 0 | Math.random() * 16;
                            uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                        }
                    }
                }

                return uuid.join('');
            }

            init();

        </script>
    </body>
</html>
